package java21demo;

public class SwitchPatternMatching {

    public static void main(String[] args) {
        Shape shape = new Square(5);
        System.out.println("Square(side = 5) area:" + calcArea(shape));

    }

    /**
     * 主要是因为有sealed interface Shape 限定了他的实现类只能有指定的那三个，编辑器可以知道case有多少种情况，所以支持了switch。
     * @param shape
     * @return
     */
    static double calcArea(Shape shape) {
        return switch (shape) {
            case Circle circle -> circle.area();
            case Rectangle rectangle -> rectangle.area();
            case Square square -> square.area();
        };
    }

    sealed interface Shape permits Circle, Rectangle, Square {
        double area();
    }

    record Circle(double radius) implements Shape {

        @Override
        public double area() {
            return Math.PI * radius * radius;
        }
    }

    record Rectangle(double length, double width) implements Shape {

        @Override
        public double area() {
            return length * width;
        }
    }

    record Square(double side) implements Shape {

        @Override
        public double area() {
            return Math.pow(side, 2);
        }
    }


}
